package com.xiaojiang.controller;

import com.xiaojiang.pojo.Category;
import com.xiaojiang.pojo.Result;
import com.xiaojiang.service.CategoryService;
import com.xiaojiang.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 功能：
 * 作者：小江
 * 日期：2024年08月06日
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public Result add(@RequestBody @Validated(value = Category.Add.class) Category category) {
        categoryService.add(category);
        return Result.success();
    }

    @GetMapping
    public Result<List<Category>> list() {
        List<Category> listInfo = categoryService.list();
        return Result.success(listInfo);
    }

    @GetMapping("/detail")
    public Result<Category> detail(Integer id) {
        Category detailInfo = categoryService.detail(id);
        return Result.success(detailInfo);
    }

    @PutMapping
    public Result update(@RequestBody @Validated(value = Category.Update.class) Category category) {
        categoryService.update(category);
        return Result.success();
    }

    @DeleteMapping
    public Result delete(Integer id) {

        if (id == null) {
            return Result.error("ID不能为空!");
        }

        List<Category> listInfo = categoryService.list();
        // 检查传入的id是否在用户的分类列表中

        Boolean found = false;
        for (Category list : listInfo) {
            if (list.getId().equals(id)) {
                found = true;
                break;
            }
        }
        if (found) {
            categoryService.delete(id);
            return Result.success();
        } else {
            return Result.error("未找到对应的类别ID");
        }

/*        if (!listInfo.contains(id)){
            // 如果id不在列表中，返回错误
            return Result.error("未找到对应的类别ID");
        }
        // 如果找到了，则执行删除操作
        categoryService.delete(id);
        return Result.success();*/

    }
}
